const openDB = function(db_name){   //打开数据库
   return new Promise((resolve,reject)=>{
      let request = window.indexedDB.open(db_name)
      request.onerror = function(event){
        console.log(event)
        reject("opendb fail"+event)
      }
      request.onsuccess = function(event){
        //console.log('onsuccess')
        resolve(event.target.result)
      }
      request.onupgradeneeded = function(event){
          console.log('DB update')         
      }
      request.onblocked = function(event){
        console.log('openDB onblocked')
      }
   })
}

const clearData = async function(db_name,objectstore_name){  //清除对象实例
     let db = await openDB(db_name)

     if(!db.objectStoreNames.contains(objectstore_name)){  //判断有无该表
        db.close()
        let cc = []
        return new Promise((resolve,reject)=>{
          return resolve(cc)
        }) 
     }

     let request = db
        .transaction(objectstore_name,'readwrite')  //指定对象实例和模式
        .objectStore(objectstore_name)  //拿到对象实例
        .clear()
        return new Promise((resolve,reject)=>{
             request.onsuccess = function(e){
              db.close()
              return resolve(e)
             }
             request.onerror = function(e){
              db.close()
              return reject(e)    
             }
        })
}

const insert = async function(db_name,objectstore_name,args){  //增加
      let db = await openDB(db_name)  //获取数据库实例
      let request = db
         .transaction(objectstore_name,'readwrite')  //指定对象实例和模式
         .objectStore(objectstore_name)  //拿到对象实例

      let add_result
      if(Object.prototype.toString.call(args) == '[object Array]'){
         args.forEach( (item)=>{
             add_result = request.add(item)
         })
      }else{
         add_result = request.add(args)
      }

      return new Promise((resolve,reject)=>{
           add_result.onsuccess = function(e){
            db.close()
            return resolve(e)
           }
           add_result.onerror = function(e){
            db.close()
            return reject(e)    
           }
      })
}

const getData = async function(db_name,objectstore_name,value,index_value,){  //读取数据
   //console.log('db getdata')
   //console.log(db_name,objectstore_name,value,index_value)
   let db = await openDB(db_name)
   if( !db.objectStoreNames.contains(objectstore_name) ){
    db.close()
    return false
   }
   let store = db
         .transaction(objectstore_name,'readwrite')  //指定对象实例和模式
         .objectStore(objectstore_name)  //拿到对象实例

   let request
   if(index_value){  //通过索引 value索引名 index_value 索引值
       let index = store.index(value)
       request = index.getAll(index_value)  //默认通过索引获取所有值,换成get获取第一个值
       
   }else{  //没有索引 通过主键
       request = store.get(value)
   }

   return new Promise((resolve,reject)=>{
       request.onsuccess = function(e){
        //console.log(e.target)
        db.close()
        return resolve(e.target.result)
       }
       request.onerror = function(e){
        db.close()
        return reject(e)
       }
   })
}

const readAll = async function(db_name,objstore_name){  //读取对象实例所有数据
   let db = await openDB(db_name)

   if(!db.objectStoreNames.contains(objstore_name)){  //判断有无该表
      db.close()
      let cc = []
      return new Promise((resolve,reject)=>{
        return resolve(cc)
      }) 
   }

   let store = db.transaction(objstore_name).objectStore(objstore_name)
   let request = store.getAll()

   return new Promise((resolve,reject)=>{
      request.onsuccess = function(e){
        db.close()
        return resolve(e.target.result)
      }
      request.onerror = function(e){
        db.close()
        return reject(e)
      }
   })
}

const readFirst = async function(db_name,objstore_name){  //读取对象实例第一条数据
  let db = await openDB(db_name)
  let store = db.transaction(objstore_name).objectStore(objstore_name)
  let cursor = store.openCursor()

  return new Promise((resolve,reject)=>{
    cursor.onsuccess = function(e){
      db.close()
      return resolve(e.target.result)
    }
    cursor.onerror = function(e){
      db.close()
      return resolve(e)
    }
  })
}

//更新 有表更新 无表新建
const update = async function(db_name,objstore_name,args,{index_name,index_unique}={}){  
   //console.log(objstore_name,index_name,index_unique)
   
   let db = await openDB(db_name)
   if( !db.objectStoreNames.contains(objstore_name) ){
      console.log('update not has '+objstore_name)

       let cc = db.version +1   
       //return
       db.close()//关闭上个连接
       //console.log('next new',db_name,objstore_name,cc)

       let request2 = window.indexedDB.open(db_name,cc )
       
       
       request2.onerror = function(event){
          console.log(event)
       }
       request2.onsuccess = function(event){
         console.log('request2.onsuccess')
         let db_success = event.target.result
         if(!args){
            console.log('args false')
            return new Promise((resolve,reject)=>{
               db_success.close()
               return resolve()
            })
         }

         let request_success = db_success.transaction(objstore_name,'readwrite')
              .objectStore(objstore_name)
              .put(args)
         db_success.close()
         return new Promise((resolve,reject)=>{
            request_success.onsuccess = function(e){
              //console.log(e)
              db_success.close()
              return resolve(e)
            }
            request_success.onerror = function(e){
              console.log(e)
              db_success.close()
              return reject(e)
            }
         })
       }
       request2.onblocked = function(event){
         console.log(event)
       }
       request2.onupgradeneeded = function(event2){
           console.log('update 数据库升级')

           let db2 = event2.target.result
           let objectStore = db2.createObjectStore(objstore_name,{keyPath:'id'})

           if(index_name){
             console.log('index_name is true')
             objectStore.createIndex(index_name, index_name, { unique: index_unique }) 
           }
           //objectStore.createIndex('bookid', 'bookid', { unique: false }) 
       }
    return
   }
   
   //console.log('update has',objstore_name)
   //console.log(args)
   let request = db.transaction(objstore_name,'readwrite')
        .objectStore(objstore_name)
        .put(args)
   
   return new Promise((resolve,reject)=>{
      request.onsuccess = function(e){
        //console.log(e)
        db.close()
        return resolve(e)
      }
      request.onerror = function(e){
        //console.log(e)
        db.close()
        return reject(e)
      }
   })
}

//格式化表  有表清空  没表新建
const format_store = async function(db_name,objstore_name,args,{index_name,index_unique}={}){  
   let db = await openDB(db_name)

   //console.log(objstore_name,index_name,index_unique)
   if(!db.objectStoreNames.contains(objstore_name)){  //判断有无该表
             let cc = db.version +1   
             db.close()//关闭上个连接
             //console.log('next new',db_name,objstore_name,cc)

             let request2 = window.indexedDB.open(db_name,cc )

             return new Promise((resolve,reject)=>{
                request2.onerror = function(event){
                   console.log(event)
                }
                request2.onsuccess = function(event){
                      // console.log(event)
                      let db_success = event.target.result
                      db_success.close()
                      console.log('format_store null success')
                      return resolve('null')
                }
                request2.onblocked = function(event){
                  console.log(event)
                }
                request2.onupgradeneeded = function(event2){
                    console.log('format_store 数据库升级')

                    let db2 = event2.target.result
                    let objectStore = db2.createObjectStore(objstore_name,{keyPath:'id'})

                    if(index_name){
                      console.log('index_name is true')
                      objectStore.createIndex(index_name, index_name, { unique: index_unique }) 
                    }
                }
             })
      
   }else{
      console.log('else')
      db.close()
      this.clearData(db_name,objstore_name)
   } 
}


//新增表
const create_table = async function(db_name,objstore_name,keyPath,{index_name,index_unique}={}){  
   let db = await openDB(db_name)

   //console.log('______________________________________________')
   //console.log(objstore_name,index_name,index_unique)
   if(!db.objectStoreNames.contains(objstore_name)){  //判断有无该表
             //console.log(db.version)
             let cc = db.version +1
             db.close()//关闭上个连接

             //console.log('next new',db_name,objstore_name,cc)

             let request2 = window.indexedDB.open(db_name,cc )

             return new Promise((resolve,reject)=>{
                request2.onerror = function(event){
                   console.log(event)
                }
                request2.onsuccess = function(event){
                      //console.log(' create_table  onsuccess')
                      let db_success = event.target.result
                      //console.log('create_table success close')
                      db_success.close()
                      //console.log('format_store null success')
                      return resolve('success')
                }
                request2.onblocked = function(event){
                  console.log(event)
                }
                request2.onupgradeneeded = function(event2){
                   //console.log('create_table 数据库升级')

                    let db2 = event2.target.result
                    let objectStore = db2.createObjectStore(objstore_name,{keyPath:keyPath})

                    if(index_name){
                      //console.log('index_name is true')
                      objectStore.createIndex(index_name, index_name, { unique: index_unique }) 
                    }


                }
             })
      
   }else{
      return new Promise((res,rej)=>{
        return res('exist')
      })
   } 
}

export default{
  insert:insert,
  create_table:create_table,
  getData:getData,
  readAll:readAll,
  readFirst:readFirst,
  clearData:clearData,
  update:update,
  format_store:format_store
}





